package o2o.web.actions.print;

import o2o.config.dao.UserDaoSql;
import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.print.PrintMessageMemory;
import o2o.cache.shop.ShopMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.print.PRINT_TYPE;
import o2o.dao.PO.print.PrintConfig;
import o2o.dao.PO.print.PrintMessage;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.web.actions.user.User;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import pay.weixin.utils.MD5Util;

import java.io.IOException;
import java.sql.SQLException;
import java.util.*;

@Controller
public class PrintBindAction {

    //  绑定打印机
    @RequestMapping(method = RequestMethod.POST, value = "/system/print/bind")
    @ResponseBody
    public String printBind(String token, Long shopId,
                            String machine_code,      // 打印机终端号
                            String mkey,              // 打印机终端密钥
                            String apiKey,            //  易联云用户密钥
                            String partner,           //  易联云用户id
                            String username,           // 易联云的用户名
                            String mobilePhone         //  易联云手机号
    ) {

        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //取得用户
        //   ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        //  根据用户拿到所属打印机的密钥
        List<ShopInfo> list = ShopMemory.getInstance().list();
        ShopInfo shopInfo = list.get(0);
        // ShopInfo shopInfo = new ShopInfo();
        // shopInfo.setShopName("admin");

        //  根据商户终端号查看是否已被绑定
        PrintMessage printMessage = getPrintFromCode(machine_code);
        if (printMessage != null) {
            return AjaxResult.errorResult("打印机已存在，请从列表查看！");
        }
        String state = null;
        PrintMessage key = null;
        key = getKey();     //    公司用的密钥

        //  得到易联云id
        //  绑定 到公司名下
        try {
            if (apiKey == null && partner == null) {
                state = printBindMethod(key.getUsername(), key.getMobilePhone(), user.getUsername(), machine_code, key.getApikey(), mkey, key.getPartner());
            } else {
                state = printBindMethod(username, mobilePhone, user.getUsername(), machine_code, apiKey, mkey, partner);
            }
        } catch (Exception e) {
            return AjaxResult.errorResult("绑定发生异常");
        }

        if ("2".equals(state)) {
            //  易联云已经绑定了，但是库里没有更新
            if (apiKey == null && partner == null) {
                updatePrint(shopId, machine_code, key.getApikey(), mkey, key.getPartner(), user.getUsername(), key.getUsername(), key.getMobilePhone());    //  绑定公司下

            } else {
                updatePrint(shopId, machine_code, apiKey, mkey, partner, user.getUsername(), username, mobilePhone);               //  绑定用户下
            }
            return AjaxResult.errorResult("该打印机已绑定易联云，已更新到列表中！");
        } else if ("3".equals(state) || "4".equals(state)) {
            return AjaxResult.errorResult("服务器异常，稍后再试");
        } else if ("5".equals(state)) {
            return AjaxResult.errorResult("用户验证失败");
        } else if ("6".equals(state)) {
            return AjaxResult.errorResult("终端号非法");
        }

        if ("1".equals(state)) {
            if (apiKey == null && partner == null) {
                updatePrint(shopId, machine_code, key.getApikey(), mkey, key.getPartner(), user.getUsername(), key.getUsername(), key.getMobilePhone());    //  绑定公司下
            } else {
                updatePrint(shopId, machine_code, apiKey, mkey, partner, user.getUsername(), username, mobilePhone);               //  绑定用户下
            }
            return AjaxResult.successResult("绑定成功");
        }
        return AjaxResult.errorResult("绑定失败");
    }

    // 解除绑定在公司的打印机
    @RequestMapping(method = RequestMethod.POST, value = "/system/print/unbind")
    @ResponseBody
    public String unBind(String token,      // 用户的唯一登陆标识
                         Long shopId,       // 商铺的ID
                         String machine_code
    ) {

        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        //ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        //  查到绑定的打印机
        PrintMessage print = getPrintFromShopID(machine_code);
        if (print == null) {
            return AjaxResult.errorResult("没有绑定的打印机");
        }
        deletePrint(machine_code);
        //  调用解绑的接口
        try {
            String result = unBind(machine_code, print.getApikey(), print.getMkey(), print.getPartner());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.successResult("解绑失败，稍后刷新重试");
        }

        return AjaxResult.successResult("解绑成功");
    }

    //  删除
    private void deletePrint(String machine_code) {
        StringBuffer sb = new StringBuffer();
        sb.append("DELETE FROM ").append(PojoTables.PRINT_MESSAGE).append(" WHERE machine_code=\'").append(machine_code).append("\'");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //  发送解绑打印机的请求
    public static String unBind(String machine_code, String apiKey, String mKey, String partner) {
        Map<String, String> params = new HashMap<>();
        params.put("partner", partner);                 //  用户id
        params.put("machine_code", machine_code);       //  打印机终端号

        String sign = signRequest(params, apiKey, mKey);

        // params.put("msign", mKey);                      //  打印机终端密钥
        params.put("sign", sign);

        HttpClient httpClient = new HttpClient();
        PostMethod post = new PostMethod("http://open.10ss.net:8888/removeprint.php");

        for (Map.Entry<String, String> entry : params.entrySet()) {
            post.addParameter(entry.getKey(), entry.getValue());
        }


        HttpMethodParams param = post.getParams();
        param.setContentCharset("UTF-8");
        try {
            httpClient.executeMethod(post);
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //如果返回200，表明成功
        String result = "";
        try {
            result = post.getResponseBodyAsString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    // 根据店铺id找到该店铺下的打印机
    private PrintMessage getPrintFromShopID(String machine_code) {
        PrintMessage printMessage = null;
        StringBuffer sb = new StringBuffer();
        /*SELECT partner,apikey,username,mobilephone FROM print_message WHERE id=1*/
        sb.append("SELECT partner,apikey,mkey,username,mobilephone FROM ").append(PojoTables.PRINT_MESSAGE).append(" WHERE machine_code=")
                .append("\'").append(machine_code).append("\' AND delflag=0");

        try {
            printMessage = (PrintMessage) UserDaoSql.getInstance().getObject(PrintMessage.class, sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return printMessage;
    }

    //   得到公司的易联云密钥
    private PrintMessage getKey() {
        PrintMessage printMessage = null;
        StringBuffer sb = new StringBuffer();
        sb.append("SELECT partner,apikey,username,mobilephone FROM ").append(PojoTables.PRINT_MESSAGE).append(" WHERE username=\'15666371607\'");

        try {
            printMessage = (PrintMessage) UserDaoSql.getInstance().getObject(PrintMessage.class, sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return printMessage;
    }


    // 更新到库里
    private void updatePrint(Long shopId, String machine_code, String apiKey, String mkey, String partner, String username, String yiLianName, String mobilePhone) {
        StringBuffer sb = new StringBuffer();
        /* INSERT INTO print_message (shopid,partner,machine_code,apikey,mkey,createUser,createTime) VALUES () */

//        sb.append("INSERT INTO ").append(PojoTables.PRINT_MESSAGE).append(" (shopid,partner,machine_code,apikey,mkey,createUser,createTime,username,mobilephone) VALUES (").append(shopId)
//                .append(",\'").append(partner).append("\',\'").append(machine_code).append("\',\'").append(apiKey).append("\',\'").append(mkey).append("\',\'")
//                .append(username).append("\',").append(System.currentTimeMillis()).append(",\'").append(yiLianName).append("\',\'").append(mobilePhone).append("\'").append(")");
        // 添加type
        sb.append("INSERT INTO ").append(PojoTables.PRINT_MESSAGE).append(" (shopid,partner,machine_code,apikey,mkey,createUser,createTime,username,mobilephone,type) VALUES (").append(shopId)
                .append(",\'").append(partner).append("\',\'").append(machine_code).append("\',\'").append(apiKey).append("\',\'").append(mkey).append("\',\'")
                .append(username).append("\',").append(System.currentTimeMillis()).append(",\'").append(yiLianName).append("\',\'").append(mobilePhone).append("\',").append(PRINT_TYPE.PRINT_TYPE_EYUNLIAN).append(")");
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    //  根据终端号获得打印机信息
    private PrintMessage getPrintFromCode(String machine_code) {
        PrintMessage printMessage = null;
        StringBuffer sb = new StringBuffer();
        /*SELECT id,shopid,partner,machine_code,apikey,mkey FROM print_message WHERE machine_code*/
        sb.append("SELECT id,shopid,partner,machine_code,apikey,mkey FROM ").append(PojoTables.PRINT_MESSAGE).append(" where machine_code=").append(machine_code);

        try {
            printMessage = (PrintMessage) UserDaoSql.getInstance().getObject(PrintMessage.class, sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return printMessage;
    }

    //  发送绑定打印机的请求
    public static String printBindMethod(String username, String mobilePhone, String shopName, String machine_code, String apiKey, String mKey, String partner) {
        Map<String, String> params = new HashMap<>();
        params.put("partner", partner);                 //  用户id
        params.put("machine_code", machine_code);       //  打印机终端号
        params.put("username", username);               //   管理中心的用户名（非商户的用户名）
        params.put("printname", shopName);                        // 打印机名称（以商户名）
        params.put("mobilephone", mobilePhone);                  // 空值
        String sign = signRequest(params, apiKey, mKey);

        //  params.put("apikey", apiKey);                   // 用户密钥
        params.put("msign", mKey);                      //  打印机终端密钥
        params.put("sign", sign);

        HttpClient httpClient = new HttpClient();
        PostMethod post = new PostMethod("http://open.10ss.net:8888/addprint.php");

        for (Map.Entry<String, String> entry : params.entrySet()) {
            post.addParameter(entry.getKey(), entry.getValue());
        }


        HttpMethodParams param = post.getParams();
        param.setContentCharset("UTF-8");
        try {
            httpClient.executeMethod(post);
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //如果返回200，表明成功
        String result = "";
        try {
            result = post.getResponseBodyAsString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    //    打印签名 Sign
    public static String signRequest(Map<String, String> params, String apiKey, String mKey) {
        Map<String, String> sortedParams = new TreeMap<String, String>();
        sortedParams.putAll(params);
        Set<Map.Entry<String, String>> paramSet = sortedParams.entrySet();
        StringBuilder query = new StringBuilder();
        query.append(apiKey);
        for (Map.Entry<String, String> param : paramSet) {
            query.append(param.getKey());
            query.append(param.getValue());
        }
        query.append(mKey);
        String encryptStr = MD5Util.MD5Encode(query.toString(), "UTF-8").toUpperCase();
        return encryptStr;
    }


    // ==========================飞鹅打印机对接 最新版=======================================================================
//  绑定打印机
    @RequestMapping(method = RequestMethod.POST, value = "/print/fe/bind")
    @ResponseBody
    public String printBind(String token, Long shopId,
                            String machine_code,      // 打印机终端号
                            String mkey,              // 打印机终端密钥
                            Integer pTime,           // 打印联数
                            Integer type,           // 打印机类型
                            String name,
                            String apiKey,            //  易联云用户密钥
                            String partner,           //  易联云用户id
                            String username,           // 易联云的用户名
                            String mobilePhone
    ) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
//        if (!User.hasShopAuth(user.getUserType())) {
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("你没有权限");
        }
        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("店铺id不能为空");
        }
        if (ValidateUtil.isNull(machine_code) || ValidateUtil.isNull(mkey)) {
            return AjaxResult.errorResult("打印机终端号和密钥不能为空");
        }
        ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
        if (shopInfo == null) {
            return AjaxResult.errorResult("店铺信息不存在，请核实");
        }
        if (pTime == null || pTime == 0) {
            pTime = 1;
        }
        if (type == null || (type != PRINT_TYPE.PRINT_TYPE_FE && type != PRINT_TYPE.PRINT_TYPE_EYUNLIAN)) {
            type = PRINT_TYPE.PRINT_TYPE_EYUNLIAN;
        }

        // 根据类型判断绑定的是哪个打印机
        if (type == PRINT_TYPE.PRINT_TYPE_EYUNLIAN) {
            PrintConfig config = null;
            if (StringUtils.isNotEmpty(apiKey)
                    && StringUtils.isNotEmpty(partner)
                    && StringUtils.isNotEmpty(username)
                    ) {
                config = new PrintConfig();
                config.setApiKey(apiKey).setEyUsername(username).setPartner(partner);
            } else {
                config = PrintMan.getEYLPrintByShopId(shopId);
            }
            return PrintMan.add_e_yunlian_print(shopInfo, shopId, machine_code, name, mkey, pTime, user.getUsername(), mobilePhone, config);
        } else {
            return PrintMan.add_fei_e_print(shopInfo, shopId, machine_code, name, mkey, pTime, user.getUsername());
        }
    }

    // 解除绑定
    @RequestMapping(method = RequestMethod.POST, value = "/print/fe/unbind")
    @ResponseBody
    public String print_unbind(String token,
                               Long printId
    ) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("你没有权限");
        }
        if (ValidateUtil.isNotID(printId)) {
            return AjaxResult.errorResult("打印机id不能为空");
        }
        PrintMessage printMessageDB = PrintMessageMemory.getInstance().getById(printId);
        if (printMessageDB == null) {
            return AjaxResult.errorResult("没有该设备号,请核实");
        }
        if (printMessageDB.getType() == null || (printMessageDB.getType() != PRINT_TYPE.PRINT_TYPE_FE && printMessageDB.getType() != PRINT_TYPE.PRINT_TYPE_EYUNLIAN)) {
            return AjaxResult.errorResult("打印机信息错误");
        }
        if (printMessageDB.getType() == PRINT_TYPE.PRINT_TYPE_FE) {
            return PrintMan.del_print_fei_e_unbind(printMessageDB);
        } else {
            return PrintMan.del_print_e_yunlian_unbind(printMessageDB);
        }
    }

    // 打开或者关闭打印机
    @RequestMapping(method = RequestMethod.POST, value = "/print/fe/open")
    @ResponseBody
    public String print_is_open(String token,
                                Long printId,
                                Integer type) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("你没有权限");
        }
        if (ValidateUtil.isNotID(printId)) {
            return AjaxResult.errorResult("打印机id不能为空");
        }
        if (type == null || (type != 0 && type != 1)) {
            return AjaxResult.errorResult("请选择操作类型");
        }
        StringBuffer sql = new StringBuffer();

        sql.append("update ").append(PojoTables.PRINT_MESSAGE)
                .append(" set updateUser ='").append(user.getUsername()).append("'")
                .append(" , isOpen=").append(type)
                .append(" where id=").append(printId);
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        // 缓存
        PrintMessageMemory.getInstance().modify(printId);
        return AjaxResult.successResult();
    }

    @RequestMapping(method = RequestMethod.POST, value = "/print/fe/feTime/modify")
    @ResponseBody
    public String print_ptime_modify(String token,
                                     Long printId,
                                     Integer pTime) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }
        if (!User.hasShopAuth(user.getUsername(), user.getUserType())) {
            return AjaxResult.errorResult("你没有权限");
        }
        if (ValidateUtil.isNotID(printId)) {
            return AjaxResult.errorResult("打印机id不能为空");
        }
        if (pTime == null) {
            return AjaxResult.errorResult("请选择打印次数");
        }
        if (pTime > 5 || pTime < 1) {
            return AjaxResult.errorResult("系统只支持打印1-5次");
        }
        StringBuffer sql = new StringBuffer();

        sql.append("update ").append(PojoTables.PRINT_MESSAGE)
                .append(" set updateUser ='").append(user.getUsername()).append("'")
                .append(" , feTime=").append(pTime)
                .append(" where id=").append(printId).append(" and delFlag = 0");
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult(e.getMessage());
        }
        // 缓存
        PrintMessageMemory.getInstance().modify(printId);
        return AjaxResult.successResult();
    }
}

